package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.bind.v2.model.core.ID;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Service
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoApi videoApi;

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    //查询好友的方法
    @Override
    public List<Publish> queryPublishList(List<Object> list, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("id").in(list).and("state").is(5)).with(pageRequest);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        return publishList;
    }

    //查询时间表
    @Override
    public List<TimeLine> queryTimeLine(Long id) {
        List<TimeLine> timeLineList = mongoTemplate.findAll(TimeLine.class, "quanzi_time_line_" + id);
        return timeLineList;
    }

    //查询推荐朋友列表
    @Override
    public List<Publish> queryRecommendList(List<Long> pidLongList, Integer page, Integer pagesize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("pid").in(pidLongList).and("state").is(5)).with(pageRequest);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        return publishList;
    }

    //发布动态
    @Override
    public void savePublish(Publish publish) {
        mongoTemplate.insert(publish);
    }

    //保存图片
    @Override
    public void saveAlbum(Album album, Long id) {
        mongoTemplate.insert(album, "quanzi_album_" + id);
    }

    //根据登录者id查询好友id
    @Override
    public List<Users> queryFriendIds(Long id) {
        Query query = Query.query(Criteria.where("userId").is(id));
        return mongoTemplate.find(query, Users.class);
    }

    //保存时间线表
    @Override
    public void saveTimeLine(Object friendId, Publish publish) {
        TimeLine timeLine = new TimeLine();
        timeLine.setUserId(publish.getUserId());
        timeLine.setPublishId(publish.getId());
        timeLine.setDate(System.currentTimeMillis());
        mongoTemplate.insert(timeLine, "quanzi_time_line_" + friendId);
    }

    //根据id查询动态
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    //点赞
    @Override
    public Boolean likeComment(Long id, String publishId) {
        //保存Comment数据
        Boolean result = this.saveComment(id, publishId, CommentType.LIKE, null);
        //保存失败
        if (!result) {
            return false;
        }
        //向redis里更新 修改点赞数
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String hashKey = CommentType.LIKE.toString();
        //采用模板对象对redis中的数据进行修改
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //用户是否点赞
        String userHashKey = COMMENT_USER_LIEK_REDIS_KEY_PREFIX + id;
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    //查询点赞数
    @Override
    public Long queryLikeCount(String publishId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LIKE.getType())
        );
        return mongoTemplate.count(query, Comment.class);
    }

    //取消点赞
    @Override
    public Boolean disLikeComment(Long id, String publishId) {
        //删除评论数据
        Boolean result = this.removeComment(id, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }
        //修改redis中的数据
        //修改点赞数
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String hashKey = CommentType.LIKE.toString();
        //采用模板对象对redis中的数据进行修改
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //用户是否点赞
        String userHashKey = COMMENT_USER_LIEK_REDIS_KEY_PREFIX + id;
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    //查询用户是否点赞该动态
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String userHashKey = COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);//1 2 3
        if (ObjectUtil.isNotEmpty(data)) {//不为空还需要比较是否为1
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;

    }

    //喜欢
    @Override
    public Boolean loveComment(Long id, String publishId) {
        //保存Comment数据
        Boolean result = this.saveComment(id, publishId, CommentType.LOVE, null);
        //保存失败
        if (!result) {
            return false;
        }
        //向redis里更新 修改喜欢数
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String hashKey = CommentType.LOVE.toString();
        //采用模板对象对redis中的数据进行修改
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //用户是否喜欢
        String userHashKey = COMMENT_USER_LOVE_REDIS_KEY_PREFIX + id;
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    //查询喜欢数
    @Override
    public Long queryLoveCount(String publishId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LOVE.getType())
        );
        return mongoTemplate.count(query, Comment.class);
    }

    //取消喜欢
    @Override
    public Boolean disLoveComment(Long id, String publishId) {
        //删除评论数据
        Boolean result = this.removeComment(id, publishId, CommentType.LOVE);
        if (!result) {
            return false;
        }
        //修改redis中的数据
        //修改喜欢数
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String hashKey = CommentType.LOVE.toString();
        //采用模板对象对redis中的数据进行修改
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //用户是否喜欢
        String userHashKey = COMMENT_USER_LOVE_REDIS_KEY_PREFIX + id;
        redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    //查询用户是否喜欢
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = COMMENT_REDIS_KEY_PREFIX + publishId;
        String userHashKey = COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);//1 2 3
        if (ObjectUtil.isNotEmpty(data)) {//不为空还需要比较是否为1
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经喜欢
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    //查询评论
    @Override
    public List<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = new Query(Criteria
                .where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);

        //查询评论列表
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        return commentList;
    }

    //发表评论
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        //调用保存方法
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    //查询评论数
    @Override
    public Long queryCommentCount(String id) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(id))
                .and("commentType").is(CommentType.COMMENT.getType())
        );
        return mongoTemplate.count(query, Comment.class);

    }

    //删除评论数据 (点赞 评价 喜欢)
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        //执行删除
        boolean result = mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
        return result;
    }

    //保存评论数据 (点赞 评价 喜欢)
    private Boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            //新建一个评论对象
            Comment comment = new Comment();
            //赋值
            comment.setId(new ObjectId());
            comment.setCommentType(commentType.getType());
            comment.setPublishId(new ObjectId(publishId));
            comment.setUserId(userId);
            //内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            //根据publishId查询动态信息 发布动态的用户id
            Publish publish = this.queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)) {
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        // 其他情况，直接返回
                        return false;
                    }
                }
            }
            this.mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }

        return false;
    }

    //根据id查询Comment对象
    private Comment queryCommentById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Comment.class);
    }

    //查询对我的点赞消息列表
    @Override
    public List<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LIKE, page, pageSize);
    }

    //查询对我的喜欢消息列表
    @Override
    public List<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    //查询对我的评论消息列表
    @Override
    public List<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    //查询评论
    public List<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        //设置分页参数
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        //设置查询条件
        Query query = new Query(Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);
        //执行查询
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }

    //查询相册
    @Override
    public List<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        //1.设置分页参数
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("created")));
        //2.设置查询条件
        Query query = new Query();
        //3.查询自己的相册表
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        //4.获取所有动态id的集合
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");
        //5.设置查询条件
        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList)
                        .and("state").is(5)).with(pageRequest)
                .with(Sort.by(Sort.Order.desc("created")));
        //6.执行查询并返回
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

        return publishList;
    }
}